const CryptoJS = require('./crypto.js');

function key_f(str = 'lFmOgzY5') {
    return CryptoJS.enc.Utf8.parse(stringToHex(str).toUpperCase());
}

function stringToHex(str) {
    var val = "";
    for (var i = 0; i < str.length; i++) {
        if (val == "")
            val = str.charCodeAt(i).toString(16);
        else
            val += str.charCodeAt(i).toString(16);
    }
    return val;
}

const AesEncode = function (word, str) {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key_f(str), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    let encryptedBase64Data = CryptoJS.enc.Hex.stringify(encrypted.ciphertext);
    return encodeURIComponent(encryptedBase64Data).toUpperCase();
}

const AesDecode = function (word, str) {
    let ciphertext = CryptoJS.enc.Hex.parse(decodeURIComponent(word));
    let decrypted = CryptoJS.AES.decrypt({ ciphertext }, key_f(str), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return decrypted.toString(CryptoJS.enc.Utf8);
}

module.exports = {
    AesEncode,
    AesDecode
};